package me.zhenqu.redis;

import java.util.List;

/**
 * Created at 11-7-6
 *
 * @author yonghui.chen
 */
public class FifoRedisList {
    private int size;
    private String category;
    private RedisOperator operator;
    private ListInitializer initializer;

    public FifoRedisList(String category, int size) {
        this.category = "list_" + category;
        operator = RedisOperator.getInstance();
        this.size = size;
    }

    public FifoRedisList(String category, int size, ListInitializer initializer) {
        this.category = "list_" + category;
        operator = RedisOperator.getInstance();
        this.size = size;
        this.initializer = initializer;
    }

    public FifoRedisList(String redisServer, String category, int size, ListInitializer initializer) {
        operator = RedisOperator.getOperator(redisServer);
        this.category = "list_" + category;
        operator = RedisOperator.getInstance();
        this.size = size;
        this.initializer = initializer;
    }

    public FifoRedisList(String redisServer, String category, int size) {
        operator = RedisOperator.getOperator(redisServer);
        this.category = "list_" + category;
        this.size = size;
    }

    public void appendItem(String key, String item) {
        long s = operator.size(category, key);
        if (s > size - 1) {
//            operator.tail(category, key);
            operator.trimList(category, key, -1, -1);
        }
        if (s == 0 && initializer != null) {
            doInit(key);
        }
        operator.prependToList(category, key, item);
    }

    private void doInit(String key) {
        long s = 0;
        List<String> initValue = initializer.getInitValue(key);
        for (String val : initValue) {
            s++;
            operator.appendToList(category, key, val);
            if (s == size - 1) break;
        }
    }

    public void clear(String key) {
        operator.remove(category, key);
    }

    public List<String> items(String key, int offset, int size) {
        if (initializer != null) {
            long s = operator.size(category, key);
            if (s == 0) {
                doInit(key);
            }
        }
        return operator.subList(category, key, offset, offset + size - 1);
    }
}
